package com.zmn.oms.business.impl.warranty;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.price.common.dto.item.ItemWarrantyDetailDRO;
import com.zmn.base.price.dubbo.interfaces.item.ItemWarrantyRemoteService;
import com.zmn.base.product.common.dto.categ.CategServProductGroupDRO;
import com.zmn.base.product.dubbo.interfaces.categ.serv.CategServProductListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.OrderGlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.business.interfaces.messageV1.common.MessageGetSendInfoService;
import com.zmn.oms.business.interfaces.product.OrderProductExtendBService;
import com.zmn.oms.business.interfaces.warranty.OrderWarrantyBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.model.dto.work.modify.OrderWarrantyUpdateDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.order.Order;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.shop.OrderShop;
import com.zmn.oms.model.entity.warranty.OrderWarranty;
import com.zmn.oms.model.entity.warranty.OrderWarrantyProduct;
import com.zmn.oms.model.entity.warranty.WarrantyQuery;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.model.vo.warranty.*;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.product.OrderProductExtendService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.shop.OrderShopService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyProductService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.saas.dubbo.dto.shop.ShopDIO;
import com.zmn.saas.dubbo.dto.shop.ShopDRO;
import com.zmn.saas.dubbo.interfaces.shop.ShopRemoteService;
import com.zmn.uuc.common.dio.user.UserRegisterByThirdAccountDIO;
import com.zmn.uuc.common.dro.user.UserThirdBaseDRO;
import com.zmn.uuc.dubbo.interfaces.user.UserListRemoteService;
import com.zmn.uuc.dubbo.interfaces.user.UserRegisterRemoteService;
import com.zmn.uuc.dubbo.interfaces.user.UserThirdListRemoteService;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：保单service实现
 *
 * @author heciqi
 * @date 2018/11/29 17:39
 */
@Service
public class OrderWarrantyBServiceImpl implements OrderWarrantyBService {

    private static final Logger logger = LoggerFactory.getLogger(OrderWarrantyBServiceImpl.class);

    @Autowired
    private OrderWarrantyService orderWarrantyService;
    @Autowired
    private OrderWarrantyProductService orderWarrantyProductService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderWorkListBService orderWorkListBService;
    @Autowired
    private OrderProductExtendBService orderProductExtendBService;
    @Autowired
    private OrderProductExtendService orderProductExtendService;
    @Autowired
    private OrderShopService orderShopService;
    @Autowired
    private OrderServiceItemService orderServiceItemService;
    @Autowired
    private MessageGetSendInfoService messageGetSendInfoService;

    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserListRemoteService userListRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserThirdListRemoteService userThirdListRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserRegisterRemoteService userRegisterRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private ChannelListRemoteService channelListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION,check = false)
    private ShopRemoteService shopRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private CategServProductListRemoteService categServProductListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private ItemWarrantyRemoteService itemWarrantyRemoteService;

    @Override
    public Integer countByUserId(Long userId, Integer type) {
        List<OrderWarranty> orderWarrantyList = orderWarrantyService.listByUserId(userId);
        if (CollectionUtils.isEmpty(orderWarrantyList)) {
            return 0;
        }

        if (NumberUtil.isNullOrZero(type)) {
            return orderWarrantyList.size();
        }

        List<OrderWarranty> collect = orderWarrantyList.stream()
                .filter(e -> Objects.equals(e.getType(), type))
                .collect(Collectors.toList());
        return collect.size();
    }

    @Override
    public WarrantyVO findWarrantyVOByOrderId(Long orderId) {

        OrderWarranty orderWarranty = orderWarrantyService.findByOrderIdByKeySrcMaster(orderId);
        if (orderWarranty == null) {
            return null;
        }

        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

        WarrantyVO warrantyVO = new WarrantyVO();
        warrantyVO.setCode(orderWarranty.getCode());
        warrantyVO.setOrderId(orderId);
        warrantyVO.setType(orderWarranty.getType());
        warrantyVO.setServCategName(orderDetail.getServCategName());
        warrantyVO.setUserId(orderWarranty.getUserId());

        // 保修卡获取最长保修时长
        if (Objects.equals(OrderConsts.ORDER_WARRANTY_TYPE_CARD, orderWarranty.getType())) {
            List<OrderWarrantyProduct> warrantyProducts = orderWarrantyProductService.listByOrderId(orderId);
            Optional<OrderWarrantyProduct> max;
            if (StringUtil.isNotBlank(orderWarranty.getCode())) { // 为空则为历史数据
                max = warrantyProducts.stream().max(Comparator.comparingInt(OrderWarrantyProduct::getMonth));
            } else {
                max = warrantyProducts.stream().max(Comparator.comparingInt(OrderWarrantyProduct::getDay));
            }
            if (max.isPresent()) {
               // Integer codeNum =warrantyProducts.stream().filter(item -> StringUtil.isNotBlank(item.getCode())).collect(Collectors.toList()).size();
                Date effectiveTime = orderWarranty.getEffectiveTime();
                Date expiredTime = max.get().getExpiredTime();
                long period = DateUtil.getTimespan(effectiveTime, expiredTime, DateUtil.UNIT_DAY);
                warrantyVO.setCode(StringUtil.isNotBlank(orderWarranty.getCode()) ? orderWarranty.getCode() : max.get().getCode());
                warrantyVO.setPeriod(period);
                warrantyVO.setExpiredTime(expiredTime);
            }
        }

        return warrantyVO;
    }

    /**
     * 通过多个订单id，查询订单保单信息
     *
     * @param orderIdList 订单id集合
     * @return 保单信息
     */
    @Override
    public List<WarrantyListOrderVO> listWarrantyByOrderIdList(List<Long> orderIdList) {
        // 订单保修卡列表
        List<OrderWarranty> orderWarrantyList = orderWarrantyService.listOrderWarrantyByOrderIdList(orderIdList);
        if (CollectionUtils.isEmpty(orderWarrantyList)) {
            return Lists.newArrayList();
        }

        // 订单保修卡详情
        List<OrderWarrantyProduct> warrantyProducts = orderWarrantyProductService.listOrderWarrantyProductByOrderIdList(orderIdList);
        if (CollectionUtils.isEmpty(warrantyProducts)) {
            return Lists.newArrayList();
        }

        Map<Long, List<OrderWarrantyProduct>> warrantyProductMap = warrantyProducts.stream().collect(Collectors.groupingBy(OrderWarrantyProduct::getWarrId));

        List<WarrantyListOrderVO> warrantyList = Lists.newArrayList();

        for (OrderWarranty orderWarranty : orderWarrantyList) {
            List<OrderWarrantyProduct> warrantyProductList = warrantyProductMap.get(orderWarranty.getWarrId());
            if (CollectionUtils.isEmpty(warrantyProductList)) {
                continue;
            }

            Optional<OrderWarrantyProduct> max = warrantyProductList.stream().filter(e -> Objects.nonNull(e.getExpiredTime())).max(Comparator.comparing(OrderWarrantyProduct::getExpiredTime));
            OrderWarrantyProduct warrantyProduct = null;
            // 获取最大保修时长
            if (max.isPresent()) {
                warrantyProduct = max.get();
            }

            if (Objects.isNull(warrantyProduct)) {
                continue;
            }

            WarrantyListOrderVO warrantyOrderVO = BeanMapper.map(warrantyProduct, WarrantyListOrderVO.class);
            if (Objects.equals(OrderConsts.ORDER_WARRANTY_TYPE_CARD, orderWarranty.getType())) {
                Date expiredTime = warrantyProduct.getExpiredTime();
                if (expiredTime == null) {
                    continue;
                }
                if (expiredTime.after(DateUtil.getNow())) {
                    warrantyOrderVO.setEffectived(true);
                    warrantyOrderVO.setRepair(true);
                }
                warrantyOrderVO.setEffectiveTime(orderWarranty.getEffectiveTime());
                warrantyOrderVO.setExpiredTime(expiredTime);
                warrantyOrderVO.setCode(StringUtil.isNotBlank(warrantyProduct.getCode()) ? warrantyProduct.getCode() : orderWarranty.getCode());
            } else {
                warrantyOrderVO.setEffectived(true);
                warrantyOrderVO.setCode(orderWarranty.getCode());
            }
            warrantyOrderVO.setOrderId(orderWarranty.getWarrId());
            warrantyOrderVO.setType(orderWarranty.getType());
            warrantyOrderVO.setUserId(orderWarranty.getUserId());
            warrantyList.add(warrantyOrderVO);
        }
        return warrantyList;
    }

    /**
     * 通过订单id查询保单信息
     *
     * @param orderId 订单id
     * @return 保单信息
     */
    @Override
    public WarrantyUserVO findWarrantyByOrderId(Long orderId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(orderId);
        if (orderWarranty == null) {
            return null;
        }

        WarrantyUserVO warrantyUserVO = new WarrantyUserVO();
        // 保单信息
        warrantyUserVO.setUserId(orderWarranty.getUserId());
        warrantyUserVO.setTypeName(OrderConsts.getWarrantyTypeName(orderWarranty.getType()));
        warrantyUserVO.setType(orderWarranty.getType());
        warrantyUserVO.setWarrantyCode(orderWarranty.getCode());
        warrantyUserVO.setEffectiveTime(orderWarranty.getEffectiveTime());

        // 保单产品
        List<WarrantyProductUserVO> warrantyProductUserVOList = null;

        // 保修卡加载保修
        if (Objects.equals(OrderConsts.ORDER_WARRANTY_TYPE_RECEIPT, orderWarranty.getType())) {
            // 收据加载产品
            List<OrderProduct> orderProductList = orderProductService.listOrderProductByOrderId(orderId);
            warrantyProductUserVOList = BeanMapper.mapList(orderProductList, WarrantyProductUserVO.class);
        } else {
            // 保修卡加载保修项
            List<OrderWarrantyProduct> warrantyProducts = orderWarrantyProductService.listByOrderId(orderId);
            warrantyProductUserVOList = BeanMapper.mapList(warrantyProducts, WarrantyProductUserVO.class);
        }

        if (StringUtil.isBlank(orderWarranty.getCode()) && warrantyProductUserVOList.size() == 1) {
            warrantyUserVO.setWarrantyCode(warrantyProductUserVOList.get(0).getCode());
        }

        // 根据服务分类ID和后台二级产品分类ID查询免责条款
        try {
            logger.info("获取免责条款信息入参 servCategId={}，categId={}", orderWork.getServCategId(), orderWork.getCategId());
            if (NumberUtil.isNotNullOrZero(orderWork.getServCategId()) && NumberUtil.isNotNullOrZero(orderWork.getCategId())) {
                com.zmn.common.dto2.ResponseDTO<CategServProductGroupDRO> responseDTO =
                        categServProductListRemoteService.getBasisProductGroupByServCateIdAndCategId(orderWork.getServCategId(), orderWork.getCategId());
                logger.info("获取免责条款信息出参 {}", JSON.toJSONString(responseDTO));
                if (responseDTO.isSuccess()) {
                    warrantyUserVO.setDisclaimer(responseDTO.getData().getDisclaimer());
                }
            }
        } catch (Exception e) {
            logger.error("#mapp#getDisclaimerByServAndCategTwoId#{}", e.getMessage(), e);
        }

        warrantyUserVO.setWarrantyProductList(warrantyProductUserVOList);

        // 设置订单信息
        warrantyUserVO.setOrderId(orderWork.getOrderId());
        warrantyUserVO.setTotalAmount(orderWork.getTotalAmount());
        warrantyUserVO.setVisitTime(orderWork.getVisitTime());
        return warrantyUserVO;
    }

    /**
     * 通过订单id和保修卡号查询保单信息
     *
     * @param orderId 订单id
     * @return 保单信息
     */
    @Override
    public WarrantyUserVO findWarrantyByOrderIdAndCode(Long orderId, String code) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(orderId);
        if (orderWarranty == null) {
            return null;
        }
        // 保单产品
        List<WarrantyProductUserVO> warrantyProductUserVOList;
        // 保单信息
        WarrantyUserVO warrantyUserVO = new WarrantyUserVO();
        warrantyUserVO.setUserId(orderWarranty.getUserId());
        warrantyUserVO.setTypeName(OrderConsts.getWarrantyTypeName(orderWarranty.getType()));
        warrantyUserVO.setType(orderWarranty.getType());
        warrantyUserVO.setWarrantyCode(orderWarranty.getCode());
        warrantyUserVO.setEffectiveTime(orderWarranty.getEffectiveTime());

        // region 仅历史数兼容处理
        if (StringUtil.isNotBlank(orderWarranty.getCode())) {
            // 保修卡加载保修
            if (Objects.equals(orderWarranty.getType(), OrderConsts.ORDER_WARRANTY_TYPE_RECEIPT)) {
                // 收据加载产品
                List<OrderProduct> orderProductList = orderProductService.listOrderProductByOrderId(orderId);
                warrantyProductUserVOList = BeanMapper.mapList(orderProductList, WarrantyProductUserVO.class);
            } else {
                // 保修卡加载保修项
                List<OrderWarrantyProduct> warrantyProducts = orderWarrantyProductService.listByOrderId(orderId);
                warrantyProductUserVOList = BeanMapper.mapList(warrantyProducts, WarrantyProductUserVO.class);
            }
            warrantyUserVO.setWarrantyProductList(warrantyProductUserVOList);
        }
        // endRegion

        if (StringUtil.isBlank(orderWarranty.getCode())) {
            WarrantyQuery query = new WarrantyQuery();
            query.setCode(code);
            query.setWarrId(orderId);
            List<OrderWarrantyProduct> warrantyProduct = orderWarrantyProductService.listByQuery(query);
            if (warrantyProduct != null && warrantyProduct.size() == 1) {
                warrantyProductUserVOList = BeanMapper.mapList(warrantyProduct, WarrantyProductUserVO.class);
                warrantyUserVO.setWarrantyProductList(warrantyProductUserVOList);
                warrantyUserVO.setWarrantyCode(code);
            }
        }

        // 根据服务分类ID和后台二级产品分类ID查询免责条款
        try {
            logger.info("获取免责条款信息入参 servCategId={}，categId={}", orderWork.getServCategId(), orderWork.getCategId());
            if (NumberUtil.isNotNullOrZero(orderWork.getServCategId()) && NumberUtil.isNotNullOrZero(orderWork.getCategId())) {
                com.zmn.common.dto2.ResponseDTO<CategServProductGroupDRO> responseDTO =
                        categServProductListRemoteService.getBasisProductGroupByServCateIdAndCategId(orderWork.getServCategId(), orderWork.getCategId());
                logger.info("获取免责条款信息出参 {}", JSON.toJSONString(responseDTO));
                if (responseDTO.isSuccess()) {
                    warrantyUserVO.setDisclaimer(responseDTO.getData().getDisclaimer());
                }
            }
        } catch (Exception e) {
            logger.error("#mapp#getDisclaimerByServAndCategTwoId#{}", e.getMessage(), e);
        }

        // 设置订单信息
        warrantyUserVO.setOrderId(orderWork.getOrderId());
        warrantyUserVO.setTotalAmount(orderWork.getTotalAmount());
        warrantyUserVO.setVisitTime(orderWork.getVisitTime());
        warrantyUserVO.setMasterName(orderWork.getMasterName());
        warrantyUserVO.setMasterId(orderWork.getMasterId());
        warrantyUserVO.setServCategName(orderWork.getShowServCategName());
        warrantyUserVO.setCompleteTime(orderWork.getCompleteTime());
        return warrantyUserVO;
    }

    /**
     * 根据用户id获取保修卡列表
     *
     * @param userId 用户id
     * @return 保单信息
     */
    @Override
    public List<WarrantyListUserVO> listWarrantyByUserId(Long userId) {

        /*
         * 新的保修卡列表页面获取规则应该是
         * 如果用户已经绑定了微信手机号
         * 则取保修卡/收据 用户是他的  + 他下的单子的保修卡/收据
         * */
        boolean bind = false;
        com.zmn.common.dto2.ResponseDTO<List<Long>> responseDTO = userListRemoteService.listUserBindMobileByUserIds(Lists.newArrayList(userId));
        logger.debug("查询是否绑定出参 ：【{}】", responseDTO);
        if (responseDTO.isSuccess() && !CollectionUtils.isEmpty(responseDTO.getData())) {
            bind = true;
        }

        logger.debug("{} 是否绑定 ：{}", userId, bind);

        // 订单Id集合
        Set<Long> orderIdSet = Sets.newHashSet();

        // 用户直接拥有的保修卡/收据
        List<OrderWarranty> orderWarranties = orderWarrantyService.listByUserId(userId);
        Set<Long> collect = orderWarranties.stream().map(OrderWarranty::getWarrId).collect(Collectors.toSet());
        orderIdSet.addAll(collect);

        logger.debug("{} 直接拥有订单号：{}", userId, JSON.toJSONString(collect));


        // 用户间接拥有的保修卡/收据 （用户绑定微信和手机号）
        if (bind) {
            OrderWorkQuery query = new OrderWorkQuery();
            query.setUserId(userId);
            query.setIncludes(Lists.newArrayList("orderId"));
            query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_COMPLETE, OrderStatusConsts.WORK_STATUS_CHECKOUT, OrderStatusConsts.WORK_STATUS_ACCOUNT));
            query.setPageSize(500);
            List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
            Set<Long> collect1 = esOrderWorkList.stream().map(EsOrderWork::getOrderId).collect(Collectors.toSet());
            orderIdSet.addAll(collect1);
            logger.debug("{} 间接拥有订单号：{}", userId, JSON.toJSONString(collect1));
        }
        if (CollectionUtils.isEmpty(orderIdSet)) {
            return Lists.newArrayList();
        }

        // 保修卡/收据数据
        List<OrderWarranty> orderWarrantyList = orderWarrantyService.listOrderWarrantyByOrderIdList(Lists.newArrayList(orderIdSet));
        if (CollectionUtils.isEmpty(orderWarrantyList)) {
            logger.debug("{} 拥有保修卡保修卡/收据数据个数为空", userId);
            return Lists.newArrayList();
        }

        logger.debug("{} 拥有保修卡保修卡/收据数据个数：{}", userId, orderWarrantyList.size());

        // 保修卡/收据数据
        List<OrderWarrantyProduct> warrantyProducts = orderWarrantyProductService.listOrderWarrantyProductByOrderIdList(Lists.newArrayList(orderIdSet));
        if (CollectionUtils.isEmpty(warrantyProducts)) {
            logger.debug("{} 拥有保修卡保修卡个数为空", userId);
            return Lists.newArrayList();
        }
        Map<Long, List<OrderWarrantyProduct>> warrantyProductMap = warrantyProducts.stream().collect(Collectors.groupingBy(OrderWarrantyProduct::getWarrId));

        // 订单数据
        OrderWorkQuery query = new OrderWorkQuery();
        query.setOrderIdList(Lists.newArrayList(orderIdSet));
        query.setPageSize(500);
        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
        Map<Long, WarrantyListVO> finalWarrantyMap = listWarrantyByWorkList(esOrderWorkList);

        logger.debug("{} 拥有保修卡对应订单数据个数：{}", userId, esOrderWorkList.size());

        // 数据组合
        List<WarrantyListUserVO> vos = Lists.newArrayList();
        for (OrderWarranty orderWarranty : orderWarrantyList) {
            if (orderWarranty.getEffectiveTime() == null) {
                continue;
            }

            Date visitTime = null;
            String productName = "";
            WarrantyListUserVO warrantyListUserVO = new WarrantyListUserVO();
            if (finalWarrantyMap.containsKey(orderWarranty.getWarrId())) {
                visitTime = finalWarrantyMap.get(orderWarranty.getWarrId()).getVisitTime();
                productName = finalWarrantyMap.get(orderWarranty.getWarrId()).getProductName();
            }

            List<OrderWarrantyProduct> warrantyProductList = warrantyProductMap.get(orderWarranty.getWarrId());

            if (StringUtil.isBlank(orderWarranty.getCode())) {
                for (OrderWarrantyProduct warrantyProduct : warrantyProductList) {
                    if (StringUtil.isBlank(warrantyProduct.getCode()) || orderWarranty.getEffectiveTime() == null) {
                        continue;
                    }
                    WarrantyListUserVO warrantyListUser = new WarrantyListUserVO();
                    warrantyListUser.setOrderId(orderWarranty.getWarrId());
                    warrantyListUser.setCode(warrantyProduct.getCode());
                    warrantyListUser.setExpiredTime(warrantyProduct.getExpiredTime());
                    warrantyListUser.setVisitTime(visitTime);
                    warrantyListUser.setProductName(StringUtil.isBlank(productName) ? warrantyProduct.getProductName() : productName);
                    warrantyListUser.setType(OrderConsts.ORDER_WARRANTY_TYPE_CARD);
                    warrantyListUser.setTypeName(OrderConsts.getWarrantyTypeName(OrderConsts.ORDER_WARRANTY_TYPE_CARD));
                    warrantyListUser.setCreateTime(warrantyProduct.getCreateTime());
                    if (warrantyProduct.getExpiredTime().after(DateUtil.getNow())) {
                        warrantyListUser.setEffectived(true);
                    } else {
                        warrantyListUser.setEffectived(false);
                    }
                    vos.add(warrantyListUser);
                }
            }

            // region 历史数兼容处理
            if (StringUtil.isNotBlank(orderWarranty.getCode())) {
                if (Objects.equals(OrderConsts.ORDER_WARRANTY_TYPE_CARD, orderWarranty.getType())) {
                    // 过期时间进行降序取第一个
                    Date expiredTime =
                            warrantyProductList.stream().sorted(Comparator.comparing(OrderWarrantyProduct::getExpiredTime, Comparator.nullsLast(Date::compareTo)).reversed())
                                    .map(OrderWarrantyProduct::getExpiredTime).collect(Collectors.toList()).get(0);

                    warrantyListUserVO.setExpiredTime(expiredTime);
                    if (expiredTime.after(DateUtil.getNow())) {
                        warrantyListUserVO.setEffectived(true);
                    } else {
                        warrantyListUserVO.setEffectived(false);
                    }
                } else {
                    warrantyListUserVO.setEffectived(true);
                }
                warrantyListUserVO.setCode(orderWarranty.getCode());
                warrantyListUserVO.setOrderId(orderWarranty.getWarrId());
                warrantyListUserVO.setTypeName(OrderConsts.getWarrantyTypeName(orderWarranty.getType()));
                warrantyListUserVO.setType(orderWarranty.getType());
                warrantyListUserVO.setCreateTime(orderWarranty.getCreateTime());
                warrantyListUserVO.setProductName(productName);
                warrantyListUserVO.setVisitTime(visitTime);
                vos.add(warrantyListUserVO);
            }
            // endRegion

        }
        return vos;
    }


    @Override
    public Map<Long, WarrantyListVO> listWarrantyByWorkList(List<EsOrderWork> esOrderWorks) {
        Map<Long, WarrantyListVO> warningMap = Maps.newHashMapWithExpectedSize(esOrderWorks.size());
        for (EsOrderWork esOrderWork : esOrderWorks) {
            WarrantyListVO vo = new WarrantyListVO();
            vo.setProductName(CollectionUtil.isNotNullOrEmpty(esOrderWork.getProductList()) ? esOrderWork.getProductList().get(0).getProductName() : null);
            vo.setVisitTime(esOrderWork.getVisitTime());
            warningMap.put(esOrderWork.getId(), vo);
        }
        return warningMap;
    }


    /**
     * 激活并领取保修卡
     */
    @Override
    public void activeAndTakeWarranty(Long orderId) {
        // 激活
        this.activeWarranty(orderId);
    }

    /**
     * 激活保修卡
     *
     * @param orderId 订单id
     * @return 激活结果
     */
    @Override
    public void activeWarranty(Long orderId) {
        OrderWarranty warranty = orderWarrantyService.findByOrderId(orderId);

        // 激活（设置为可用状态）
        if (warranty != null) {
            orderWarrantyService.activeWarranty(orderId);
            // 重新设置过期时间
            List<OrderWarrantyProduct> warrantyProducts = orderWarrantyProductService.listByOrderId(orderId);
            if (!CollectionUtils.isEmpty(warrantyProducts)) {
                Date curDate = new Date();

                for (OrderWarrantyProduct warrantyProduct : warrantyProducts) {
                    if (warrantyProduct.getDay() != null ) {
                        // 过期时间
                        Date expiredTime = DateUtil.addDays(warranty.getEffectiveTime() == null ? new Date() : warranty.getEffectiveTime(), warrantyProduct.getDay());
                        warrantyProduct.setExpiredTime(expiredTime);
                        orderWarrantyProductService.updateExpiredTime(warrantyProduct);
                    }

                    // region 此处是师傅端APP发版期间的兼容处理 后期可以删除 by 20200806
                    if (warrantyProduct.getMonth() != null) {
                        Date expiredTime = DateUtil.getBaseDefer(DateUtil.toString(curDate), DateUtil.FORMAT_DATE, 0, warrantyProduct.getMonth(), 0, 0, 0, -1);
                        warrantyProduct.setExpiredTime(expiredTime);
                        orderWarrantyProductService.updateExpiredTime(warrantyProduct);
                    }
                    // endRegion
                }
            }

            return;
        }

        // 新保修卡没有收据,已向产品确认 此处不保留该逻辑
        // 激活时不存在保修卡，由系统根据产品自动创建
       // this.sysCreateWarranty(orderId);
    }

    /**
     * 系统生成保修卡
     *
     * @param orderId
     */
    private void sysCreateWarranty(Long orderId) {

        OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, orderId);

        // 1，新增保单
        Date curDate = new Date();
        OrderWarranty warranty = new OrderWarranty();
        warranty.setWarrId(orderId);
        warranty.setType(OrderConsts.ORDER_WARRANTY_TYPE_RECEIPT);
        warranty.setGrantTime(curDate);
        //warranty.setCode(code);
        warranty.setStatus(OrderConsts.ORDER_WARRANTY_STATUS_VALID);
        warranty.setEffectiveTime(curDate);

        Long warrantyUserId = null;

        // A 上门用户（前置用户）> 支付用户 > B 支付宝渠道 > C 下单用户绑定微信
        Long visitUserId = orderWork.getVisitUserId();
        Long customerId = orderWork.getCustomerId();
        boolean isAliChannel = Objects.equals(GlobalConsts.CHANNEL_ALIPAY_SERV_ID, orderWork.getChannelId()) || Objects.equals(GlobalConsts.CHANNEL_ALIPAY_APP_ID, orderWork.getChannelId());

        // 调用 uuc 接口，xiewenbing 2020-11-16   TODO
        com.zmn.common.dto2.ResponseDTO<UserThirdBaseDRO> openIdResponseDTO = null;
        boolean supportC = openIdResponseDTO.isSuccess() && StringUtil.isNotBlank(openIdResponseDTO.getData().getOpenId());

        if (!NumberUtil.isNullOrZero(visitUserId)) {
            warrantyUserId = visitUserId;
        } else if (!NumberUtil.isNullOrZero(customerId)) {
            warrantyUserId = customerId;
        } else if (isAliChannel) {
            warrantyUserId = orderWork.getUserId();
        } else if (supportC) {
            warrantyUserId = orderWork.getUserId();
        }

        if (Objects.nonNull(warrantyUserId)) {
            warranty.setUserId(warrantyUserId);
            warranty.setGrantTime(DateUtil.getNow());
        } else {
            OrderShop orderShop = orderShopService.findByKey(orderWork.getWorkId());
            logger.info("#CompleteOrder#sysCreateWarranty {}店铺信息：{}", orderWork.getWorkId(), JSON.toJSONString(orderShop));
            if (!Objects.isNull(orderShop)) {
                // 根据shopId获取shop是否是微信或者支付宝平台应用
                ShopDIO shopDIO = new ShopDIO();
                shopDIO.setShopId(orderShop.getShopId());
                logger.info("#CompleteOrder#sysCreateWarranty 获取店铺信息：{}", JSON.toJSONString(shopDIO));
                ResponseDTO<ShopDRO> shopResponse = shopRemoteService.getShop(shopDIO);
                logger.info("#CompleteOrder#sysCreateWarranty 获取店铺信息结果：{}", JSON.toJSONString(shopDIO));
                if (!shopResponse.getStatusBool()) {
                    logger.info("#CompleteOrder#sysCreateWarranty 自动领取保修卡失败：工单号{}", orderId);
                } else {
                    ShopDRO shopDRO = shopResponse.getData();
                    // 应用平台标志：1.微信，2支付宝，3头条，4美团
                    if (Objects.equals(shopDRO.getAppPlat(), new Byte((byte) 1)) || Objects.equals(shopDRO.getAppPlat(), new Byte((byte) 2))) {
                        Order order = orderService.findOrderByKey(orderId);
                        warranty.setUserId(order.getUserId());
                    }
                }
            } else {
                warranty.setUserId((long) GlobalConsts.NONE);
            }
        }
        logger.info("#order#warranty#syscreatewarranty orderid：{} visitUserId:{} isAliChannel: {}, openIdResponseDTO:{} ", orderWork.getOrderId(), visitUserId, isAliChannel, JSON.toJSONString(openIdResponseDTO));
        orderWarrantyService.insertWarranty(warranty);

        // 2，删除保单产品
        orderWarrantyProductService.deleteByOrderId(orderId);

        // 3，生成新的保单产品
        List<OrderProductExtend> orderProductExtend = orderProductExtendBService.getOrderProductExtend(orderId);
        if (CollectionUtils.isEmpty(orderProductExtend)) {
            return;
        }

        List insertList = new ArrayList<OrderWarrantyProduct>();
        for (OrderProductExtend productExtend : orderProductExtend) {
            OrderWarrantyProduct warrantyProduct = new OrderWarrantyProduct();
            warrantyProduct.setWarrId(orderId);
            warrantyProduct.setProExtId(productExtend.getProExtId());
            warrantyProduct.setProductId(productExtend.getProductId());
            warrantyProduct.setProductName(productExtend.getProductName());
            warrantyProduct.setMonth(GlobalConsts.NONE);
            warrantyProduct.setDay(GlobalConsts.NONE);
            warrantyProduct.setCreateTime(curDate);
            warrantyProduct.setCode(StringUtil.getRandomsString(7));
            insertList.add(warrantyProduct);
        }
        orderWarrantyProductService.insertAll(insertList);
    }

    /**
     * 领取保修卡
     *
     * @param orderId 订单id
     * @return 激活结果
     */
    @Override
    public void takeWarranty(Long orderId, Long userId) {
        orderWarrantyService.takeWarranty(orderId, userId);
    }

    @Override
    public WarrantyVO bind(String openId, Long orderId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

        // 已绑定 无需重复绑定保修卡
        WarrantyVO vo = findWarrantyVOByOrderId(orderId);
        Long warrantyUserId = vo.getUserId();

        // 已经绑定
        if (!NumberUtil.isNullOrZero(warrantyUserId)) {
            String uucOpenId = messageGetSendInfoService.getOrderUserRelationOpenId(orderId, orderWork.getPlatWork(), warrantyUserId);
            if (StringUtil.isNotBlank(uucOpenId)) {
                vo.setBind(false);
                vo.setMsg("保修卡发放成功");
                return vo;
            }
        }

        // 渠道信息
        com.zmn.common.dto2.ResponseDTO<ChannelDRO> channelResponseDTO = channelListRemoteService.getByChannelId(GlobalConsts.CHANNEL_WEIXIN_ID);
        ChannelDRO channelDRO = channelResponseDTO.getData();

        // 可以绑定
        UserRegisterByThirdAccountDIO userRegisterByThirdAccountDIO = new UserRegisterByThirdAccountDIO();
        userRegisterByThirdAccountDIO.setOpenId(openId);
        userRegisterByThirdAccountDIO.setUnionId(openId);
        userRegisterByThirdAccountDIO.setPlat(orderWork.getPlat());
        userRegisterByThirdAccountDIO.setUserName("未知");
        userRegisterByThirdAccountDIO.setGender(GlobalDict.GENDER_NO);
        userRegisterByThirdAccountDIO.setChannelId(GlobalConsts.CHANNEL_WEIXIN_ID);
        userRegisterByThirdAccountDIO.setChannelName(channelDRO.getName());
        userRegisterByThirdAccountDIO.setEntrance(orderWork.getReceiveEntranceId());
        logger.info("registerByThirdAccount 入参 ：userThirdInfoRegisterDIO:{}", JSON.toJSONString(userRegisterByThirdAccountDIO));

        // 修改调用uuc接口  xiewenbing  2020-11-16
        com.zmn.common.dto2.ResponseDTO<Long> registerDTO = userRegisterRemoteService.registerByThirdAccount(userRegisterByThirdAccountDIO);

        logger.info("registerByThirdAccount 出参 ： data:{}", JSON.toJSONString(registerDTO));
        if (!registerDTO.isSuccess()) {
            vo.setBind(false);
            vo.setMsg("绑定失败");
            return vo;
        }

        // 绑定
        takeWarranty(orderId, registerDTO.getData());
        vo.setBind(true);
        return vo;
    }

    @Override
    public void updateWarrantyMonth(Long orderId, Integer month) {

        if (Objects.isNull(orderId) || Objects.isNull(month)) {
            logger.error("#oms#updateWarrantyMonth orderId:{}, month:{} 参数错误", orderId, month);
            return;
        }

        // 校验订单状态
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        if (orderWork == null || orderWork.getStatus() < OrderGlobalConsts.WORK_STATUS_COMPLETE || Objects.isNull(orderWork.getCompleteTime())) {
            logger.error("#oms#updateWarrantyMonth orderId:{}, month:{} 订单未完成", orderId, month);
            return;
        }

        // 校验保修卡类型
        OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(orderId);
        if (!Objects.equals(orderWarranty.getType(), OrderConsts.ORDER_WARRANTY_TYPE_CARD)) {
            logger.error("#oms#updateWarrantyMonth orderId:{}, month:{} 不是保修卡", orderId, month);
            return;
        }

        // 校验保修明细
        List<OrderWarrantyProduct> orderWarrantyProductList = orderWarrantyProductService.listByOrderId(orderId);
        if (orderWarrantyProductList.isEmpty()) {
            logger.error("#oms#updateWarrantyMonth orderId:{}, month:{} 保修明细不存在", orderId, month);
            return;
        }

        Date completeTime = orderWork.getCompleteTime();

        orderWarrantyProductService.updateWarrantyMonth(orderId, completeTime, month);
    }


    @Override
    public Map<Long, Integer> isExistWarrantyInfoMap(Long orderId, Long workId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);

        // 查询订单产品 + 展开
        List<OrderProductExtend> orderProductExtendList = orderProductExtendService.listByOrderId(orderId);
        // 服务项
        List<OrderServiceItem> orderServiceItemList = orderServiceItemService.listByOrderId(orderId);

        Set<Long> collect = orderServiceItemList.stream().map(e -> e.getProExtId()).collect(Collectors.toSet());

        Map<Long, List<OrderServiceItem>> serviceItemMap = orderServiceItemList.stream().collect(Collectors.groupingBy(OrderServiceItem::getProExtId));

        Map<Long, Integer> warrantyMap = Maps.newHashMapWithExpectedSize(orderProductExtendList.size());
        for (OrderProductExtend productExtend : orderProductExtendList) {
            // 服务项未填写完整
            if (!Objects.equals(orderProductExtendList.size(), collect.size())) {
                warrantyMap.put(productExtend.getProExtId(), GlobalConsts.NO);
                continue;
            }

            List<OrderServiceItem> orderServiceItem = serviceItemMap.get(productExtend.getProExtId());
            Set<Integer> itemIds = orderServiceItem.stream().map(OrderServiceItem::getServItemId).collect(Collectors.toSet());
            Integer productId = NumberUtil.isNullOrZero(productExtend.getProductId()) ? orderWork.getProductId() : productExtend.getProductId();

            // 后台产品为空
            if (NumberUtil.isNullOrZero(productId)) {
                warrantyMap.put(productExtend.getProExtId(), GlobalConsts.NO);
                continue;
            }

            // 为空不调用接口
            if (CollectionUtil.isNullOrEmpty(itemIds)) {
                warrantyMap.put(productExtend.getProExtId(), GlobalConsts.NO);
                continue;
            }

            logger.info("订单号={}, 获取保修卡信息入参 plat={}，product={}，itemIds={}", orderWork.getOrderId(), orderWork.getPlatWork(), productId, itemIds);
            com.zmn.common.dto2.ResponseDTO<ItemWarrantyDetailDRO> resp = itemWarrantyRemoteService.getByProductIdAndItemIdList(productId, Lists.newArrayList(itemIds));

            logger.info("订单号={}, 获取保修卡信息出参 {}", orderWork.getOrderId(), JSON.toJSONString(resp));
            if (!resp.isSuccess()) {
                warrantyMap.put(productExtend.getProExtId(), GlobalConsts.NO);
            } else {
                ItemWarrantyDetailDRO warrantyItem = resp.getData();
                if (warrantyItem == null || CollectionUtils.isEmpty(warrantyItem.getContentOptionList())) {
                    warrantyMap.put(productExtend.getProExtId(), GlobalConsts.NO);
                } else {
                    warrantyMap.put(productExtend.getProExtId(), GlobalConsts.YES);
                }
            }
        }
        return warrantyMap;
    }

    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_UPDATE_WARRANTY)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void autoAddWarrantyDay(OrderWarrantyUpdateDTO warrantyUpdateDTO) {
        Integer day = warrantyUpdateDTO.getAddDay();
        if (NumberUtil.isNotNullOrZero(warrantyUpdateDTO.getOldDay())) {
            day = day + warrantyUpdateDTO.getOldDay();
        }
        // 多张保修卡选其中一张保修卡，进行延保
        OrderWarrantyProduct warrantyProduct = BeanMapper.map(warrantyUpdateDTO, OrderWarrantyProduct.class);
        warrantyProduct.setDay(day);
        orderWarrantyProductService.updateExpiredTime(warrantyProduct);
    }

}
